// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import 'normalize.css/normalize.css'
import '@/assets/iconfont/iconfont'
import IconSvg from '@/components/Icon-svg/index.vue'
import {
    getToken,
    getSite
} from '@/utils/auth'
import VueLazyload from 'vue-lazyload'
import VueDragula from 'vue-dragula';

Vue.use(VueDragula);

Vue.config.productionTip = false

Vue.use(VueLazyload, {
    error: require('@/assets/images/broken-image.svg'),
    loading: require('@/assets/images/loading-spin.svg'),
})

Vue.use(ElementUI);
Vue.component('icon-svg', IconSvg)

const whiteList = ['/login'];
router.beforeEach((to, from, next) => {

    NProgress.start();
    if (getToken() && getSite()) {
        if (to.path === '/login') {
            next({
                path: '/'
            });
        } else {
            if (store.getters.roles.length === 0) {
                store.dispatch('GetInfo').then(res => {
                    const roles = res.data.role;
                    store.dispatch('GenerateRoutes', {
                        roles
                    }).then(() => {
                        router.addRoutes(store.getters.addRouters);
                        next({ ...to
                        });
                    })
                })
            } else {
                next();
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login');
            NProgress.done();
        }
    }
});

// router.beforeRouteUpdate ((to, from, next) => {
//   console.log(to)
//   console.log(from)
//   console.log(next)
//   // 在当前路由改变，但是该组件被复用时调用
//   // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
//   // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
//   // 可以访问组件实例 `this`
// }),

router.afterEach(() => {
    NProgress.done();
});

function clearAllCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;)
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
}
clearAllCookie();
new Vue({
    el: '#app',
    router,
    store,
    template: '<App/>',
    components: {
        App
    }
})
